package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 发布小视频
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        try {
            //校验
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                return null;
            }

            //设置id
            video.setId(ObjectId.get());
            video.setVid(this.idService.createId(IdType.VIDEO));

            //发布时间
            video.setCreated(System.currentTimeMillis());

            //保存到Mongodb中
            this.mongoTemplate.save(video);

            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }

    /**
     * 分页查询小视频列表，按照时间倒序排序
     *
     * @Param: [useId, pageNum, pageSize]
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer pageNum, Integer pageSize) {
        PageInfo<Video> pageInfo = null;
        try {
            pageInfo = new PageInfo<>();
            pageInfo.setPageNum(pageNum);
            pageInfo.setPageSize(pageSize);

            //1.先从redis中查询小视频推荐列表，分页排序
            String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
            String userIdsStr = redisTemplate.opsForValue().get(redisKey);
            //存储分页查询来的小视频推荐id
            List<Long> vids = new ArrayList<>();

            int recommendCount = 0; //记录查询到的推荐总条数
            //手动排序页码
            if (ObjectUtil.isNotEmpty(userIdsStr)) {
                //手动分页查询数据
                List<String> vidList = StrUtil.split(userIdsStr, ',');

                //计算分页[0,10]
                int[] startEnd = PageUtil.transToStartEnd(pageNum - 1, pageSize);
                int startIndex = startEnd[0]; //index=0
                //min(10,vidList.size())-->9 ,取两者较小值，避免空指针
                int endIndex = Math.min(startEnd[1], vidList.size());

                for (int i = startIndex; i < endIndex; i++) {
                    // vids.add(Long.valueOf(vidList.get(i)));
                    //hutool jar包中的工具类Convert进行数据类型之间的转换
                    vids.add(Convert.toLong(vidList.get(i)));
                }
                recommendCount = vidList.size();//推荐总条数
            }

            //TODO  当推荐小视频分页查询到的条数小于总页数条数，怎么从系统的视频数据中添加补充上来，并且后面的视频不重复？？？

            //2.没有推荐或前面推荐已经查询完毕，查询系统的视频数据
            if (CollUtil.isEmpty(vids)) {
                //计算前面的推荐视频页数（系统视频数据，分页的话，还是得从第一页开始，否则数据丢失，页码需要相减）
                int totalPage = PageUtil.totalPage(recommendCount, pageSize);//推荐总页码
                pageNum = pageNum - totalPage - 1;

                //分页查询系统视频
                PageRequest pageRequest = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Order.desc("created")));
                Query query = new Query().with(pageRequest);
                List<Video> videosList = mongoTemplate.find(query, Video.class);//不用考虑推荐小视频，直接返回
                pageInfo.setRecords(videosList);
                return pageInfo;
            }

            //查询并返回推荐的小视频
            Query query = Query.query(Criteria.where("vid").in(vids));
            List<Video> videos = mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videos);
            return pageInfo;

        } catch (Exception e) {
            log.error("查询小视频列表失败~~~,pageInfo=" + pageInfo, e);
        }

        return pageInfo;

    }



    /**
     * @Description: 关注用户
     * @Param:  [userId, followUserId]
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        try {
            //需要将用户的关注列表，保存到redis中，方便后续的查询
            //使用redis的hash结构
            if (this.isFollowUser(userId, followUserId)) {
                return false;
            }

            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());

            this.mongoTemplate.save(followUser);

            //保存数据到redis
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }

    /**
     * @Description: 撤销关注
     * @Param: [userId, followUserId]
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }

        //取消关注，删除关注数据即可
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);
        if (result.getDeletedCount() > 0) {
            //同时删除redis中的数据
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);

            return true;
        }

        return false;
    }

    /**
     * @Description: 是否关注
     * @Param: [userId, followUserId]
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }


    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
        // 查询前5个访客数据，按照访问时间倒序排序
        // 如果用户已经查询过列表，记录查询时间，后续查询需要按照这个时间往后查询

        // 上一次查询列表的时间
        Long date = Convert.toLong(this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, String.valueOf(userId)));

        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(pageRequest);
        if (ObjectUtil.isNotEmpty(date)) {
            query.addCriteria(Criteria.where("date").gte(date));
        }
        return this.queryList(query, userId);
    }

    private List<Visitors> queryList(Query query, Long userId){
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        //查询每个来访用户的得分
        for (Visitors visitors : visitorsList) {

            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId())
            );
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if(ObjectUtil.isNotEmpty(recommendUser)){
                visitors.setScore(recommendUser.getScore());
            }else {
                //默认得分
                visitors.setScore(90d);
            }
        }

        return visitorsList;
    }

    @Override
    public PageInfo<Visitors> topVisitor(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Visitors> visitorsList = this.queryList(query, userId);

        PageInfo<Visitors> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(visitorsList);

        //记录当前的时间到redis中，在首页查询时，就可以在这个时间之后查询了
        String redisKey = VISITOR_REDIS_KEY;
        String hashKey = String.valueOf(userId);
        String value = String.valueOf(System.currentTimeMillis());
        this.redisTemplate.opsForHash().put(redisKey, hashKey, value);

        return pageInfo;
    }


}


